import os
from apscheduler.schedulers.background import BackgroundScheduler
from channels.layers import get_channel_layer
from asgiref.sync import async_to_sync
import psutil, json

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'application.settings')
channel_layer = get_channel_layer()
def send_group_message():
    async_to_sync(channel_layer.group_send)(
        'my_group',
        {'type': 'send_messages', 'message': 'my_group'}
    )
    async_to_sync(channel_layer.group_send)(
        'app',
        {'type': 'send_messages', 'message': 'app'}
    )

def send_group_pong():
    async_to_sync(channel_layer.group_send)(
        'pong',
        {'type': 'send_messages', 'message': 'pongs1'}
    )

# sysinfo
def send_group_sys_info():
    result = {"type": "sys"}
    result['memory'] = psutil.virtual_memory()
    result['cpu'] = psutil.cpu_percent(interval=0.01)
    disksPartitions = psutil.disk_partitions()
    disk = []
    result['disk'] = disk
    for diskpartition in disksPartitions:
        if diskpartition.fstype == "squashfs":
            continue
        device = {}
        disk.append(device)
        device['path'] = diskpartition.device
        device['free'] = psutil.disk_usage(diskpartition.mountpoint).free
        device['total'] = psutil.disk_usage(diskpartition.mountpoint).total
    async_to_sync(channel_layer.group_send)(
        'sysinfo',
        {'type': 'send_messages', 'message': json.dumps(result)}
    )

scheduler = BackgroundScheduler(name="websocket-task")

scheduler.configure(**{
    'apscheduler.executors.default.max_workers': 4,
})

scheduler.add_job(send_group_sys_info, trigger='interval', seconds=2)
scheduler.add_job(send_group_pong, trigger='interval', seconds=10)
scheduler.add_job(send_group_message, trigger='interval', seconds=2)
scheduler.start()
    
